<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <template #header>
        <div>
          <span>
            <el-button type="primary" size="default" :icon="Plus"
            @click="addTrademark"
              >添加</el-button
            >
          </span>
        </div>
      </template>
      <!-- card body -->
      <el-table border stripe :data="tableData">
        <el-table-column
          label="序号"
          type="index"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column label="品牌名称" prop="tmName"> </el-table-column>
        <el-table-column label="品牌Logo" prop="logoUrl">
          <template #default="{ row }">
            <img height="60" :src="row.logoUrl" alt="" />
          </template>
        </el-table-column>
        <el-table-column label="操作" >
          <template #default="{row}">
            <el-button type="warning" size="default" @click="updateTrademark(row)" :icon="Edit"
            >修改</el-button
          >
          <el-button type="danger" size="default" @click="deleteTrademark(row.id)" :icon="Delete"
            >删除</el-button
          >
          </template>
        </el-table-column>
      </el-table>
      <!-- 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
         -->
      <el-pagination
        v-model:page-size="limit"
        v-model:current-page="page"
        :pager-count="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[3, 5, 7, 9]"
      />
    </el-card>
    <el-dialog
      v-model="dialogFormVisible"
      :title="newTrademark.id ? '修改品牌' : '添加品牌'"
    >
      <el-form label-width="100px" :model="newTrademark" :rules="trademarkRule" ref="ruleFormRef"> 
        <el-form-item label="品牌名称" prop="tmName">
          <el-input autocomplete="off" v-model="newTrademark.tmName" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${baseUrl}/admin/product/upload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="newTrademark.logoUrl"
              :src="newTrademark.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="updateOrAddTrademark"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Trademark",
});
</script>

<script setup lang="ts">
import { ref, toRefs, onMounted, watch, reactive } from "vue";
import { Plus, Edit, Delete,  } from "@element-plus/icons-vue";
import { getAddProductRequest, getDeleteProductRequest, getProductListRequest, getReviseProductRequest, type ProductReturnType } from "@/api/product";
import type { TrademarkListItemType } from "@/api/product";
import { ElMessage ,ElMessageBox, type FormInstance, type FormRules} from "element-plus";
import type { UploadProps } from "element-plus";
//页码逻辑
interface pageDateType {
  page: number;
  limit: number;
  total: number;
}
const pageDate = ref<pageDateType>({
  page: 1,
  limit: 3,
  total: 100,
});
const { page, limit, total } = toRefs(pageDate.value);

//babel 的数据
const tableData = ref<TrademarkListItemType>([]);

//获取品牌列表
const getTrademarkList = async () => {
  const re = await getProductListRequest({
    page: page.value,
    limit: limit.value,
  });
  
  //获取数据赋值给table
  tableData.value = re.records;
  //总条数赋值给total
  total.value = re.total;
};

//调用getTrademarkList
onMounted(() => {
  getTrademarkList();
});

//监听page / limit 的变化
watch([page, limit], () => {
  getTrademarkList();
});

//4.弹窗逻辑
//控制弹窗显示隐藏的数据
const dialogFormVisible = ref(false);
const baseUrl = import.meta.env.VITE_API_URL;
const newTrademark = ref<ProductReturnType>({
  logoUrl: "",
  tmName: "",
  id: 0,
});
//上传逻辑

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  newTrademark.value.logoUrl = response.data;
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};

//添加逻辑

const addTrademark = () => {
  //先清空上一次可能残留的校验信息
  ruleFormRef.value?.clearValidate();
  dialogFormVisible.value = true;
  newTrademark.value = {
    logoUrl: "",
    tmName: "",
    id: 0,
  };
};

//修改逻辑
const updateTrademark = async (row: ProductReturnType) => {
  //先清空上一次可能残留的校验信息
  ruleFormRef.value?.clearValidate();
  dialogFormVisible.value = true;
  //获取当前的数据然后进行回填数据
  //拿到当前的数据浅拷贝赋值给表单的数据newTrademark(为了数据不会互相影响)
  newTrademark.value = { ...row };
};

//新增和修改提交
//获取form表单的实例
  const ruleFormRef = ref<FormInstance>();
const updateOrAddTrademark = async () => {
  //先进行全局校验
  try {
    await ruleFormRef.value?.validate();
    dialogFormVisible.value = false;
  
    try{
      if (newTrademark.value.id) {
      //修改提交
      await getReviseProductRequest(newTrademark.value);
      ElMessage.success("修改成功");
    } else {
      //新增提交
      await getAddProductRequest(newTrademark.value);
      ElMessage.success("新增成功");
      page.value = 1;
    }
    getTrademarkList();
    }catch(e){
      ElMessage(newTrademark.value.id ? "修改错误" : "新增错误");
    }
  } catch (e) {
    ElMessage("请填写合法的值");
  }
 
};
//删除逻辑
const deleteTrademark = async (id:number) => {
  ElMessageBox.confirm("确定要删除?" , "警告", {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: "warning",
    })
    .then( async () => {
      try{
    await getDeleteProductRequest(id);
      ElMessage.success("删除成功");
      // page.value = 1;
    }catch(e){
      ElMessage.error("删除失败");
    }
    getTrademarkList();
    })
    .catch(() => {
      ElMessage.info("取消删除");
    })
}

//表单校验逻辑
const trademarkRule = reactive<FormRules>({
  tmName: [
    { required: true, message: "必须填写品牌名称", trigger: "blur" },
    { min: 2, max: 5, message: "长度必须是2-5", trigger: "blur" },
  ],
  logoUrl: [{ required: true, message: "必须上传图片", trigger: "change" }]
})

</script>
<style scoped>
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  </style>
  
  <style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
  </style>